/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.datastore.database;

import at.schauer.gregor.vienna.context.ViennaContext;
import at.schauer.gregor.vienna.datastore.StorageMetadata;
import at.schauer.gregor.vienna.datastore.database.querybuilder.QueryBuilder;
import at.schauer.gregor.vienna.serializer.Serializer;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author Gregor Schauer
 */
public class QueryBuilderDatabaseDataStore<T> extends AbstractDatabaseDataStore<T, Map<String, Object>> {
	protected ColumnMapRowMapper rowMapper = new ColumnMapRowMapper();
	protected QueryBuilder queryBuilder;

	public QueryBuilderDatabaseDataStore(ViennaContext ctx, JdbcTemplate template, QueryBuilder queryBuilder) {
		super(ctx, template);
		this.queryBuilder = queryBuilder;
	}

	@Override
	protected <E extends T> Map<String, Object> read(StorageMetadata<E> metadata) {
		createEntityIfNecessary(metadata);

		String sql = queryBuilder.getQuery(QueryBuilder.READ);
		Object[] parameters = queryBuilder.getParameters(QueryBuilder.READ, metadata);
		Map<String, Object> map = template.queryForObject(sql, rowMapper, parameters);

		map.put(Serializer.CLASS, metadata.type.getName());
		return map;
	}

	@Override
	protected <E extends T> E map(Map<String, Object> data, StorageMetadata<E> metadata) {
		Serializer<E> serializer = ctx.getSerializer(metadata.type);
		return serializer.load(data);
	}

	@Override
	protected Object insert(StorageMetadata<T> metadata) {
		return execute(QueryBuilder.INSERT, metadata);
	}

	@Override
	protected void update(StorageMetadata<T> metadata) {
		execute(QueryBuilder.UPDATE, metadata);
	}

	protected Object execute(String key, StorageMetadata<T> metadata) {
		createEntityIfNecessary(metadata);

		Serializer<T> serializer = ctx.getSerializer(metadata.type);
		Map<String, Object> map = serializer.save(metadata.object);
		map.put(metadata.identifierName, metadata.identifier);

		String sql = queryBuilder.getQuery(key);
		Object[] parameters = queryBuilder.getParameters(key, map);
		template.update(sql, parameters);

		return metadata.identifier;
	}

	@Override
	public void delete(T obj) {
		StorageMetadata<T> metadata = StorageMetadata.create(ctx, obj);
		createEntityIfNecessary(metadata);

		String sql = queryBuilder.getQuery(QueryBuilder.DELETE);
		Object[] parameters = queryBuilder.getParameters(QueryBuilder.DELETE, metadata);
		template.update(sql, parameters);
	}

	@Override
	public <E extends T> Collection<E> list(Class<E> type) {
		StorageMetadata<E> metadata = StorageMetadata.create(ctx, type);
		createEntityIfNecessary(metadata);

		String sql = queryBuilder.getQuery(QueryBuilder.LIST);
		Object[] parameters = queryBuilder.getParameters(QueryBuilder.LIST, metadata);
		List<Map<String, Object>> maps = template.queryForList(sql, parameters);

		List<E> objects = new ArrayList<E>(maps.size());
		for (Map<String, Object> map : maps) {
			map.put(Serializer.CLASS, metadata.type.getName());
			metadata.identifier = map.get(metadata.identifierName);
			objects.add(map(map, metadata));
		}
		return objects;
	}

	protected void createEntityIfNecessary(StorageMetadata<? extends T> metadata) {
		if (!getTables().contains(metadata.entityName)) {
			String sql = queryBuilder.getQuery(QueryBuilder.CREATE);
			template.execute(sql);
			getTables().add(metadata.entityName);
		}
	}
}
